package com.ys.service.report.impl;

import com.ys.entity.report.ReFinanceExamine;
import com.ys.mapper.report.ReFinanceExamineDiyMapper;
import com.ys.mapper.report.ReFinanceExamineMapper;
import com.ys.service.report.ReFinanceExamineService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@Service("reFinanceExamineService")
public class ReFinanceExamineServiceImpl implements ReFinanceExamineService {
	private static final Logger logger = LoggerFactory.getLogger(ReFinanceExamineServiceImpl.class);
	@Autowired
	private ReFinanceExamineDiyMapper reFinanceExamineDiyMapper;
	@Autowired
	private ReFinanceExamineMapper reFinanceExamineMapper;


	/**
	 * 新增财务核账表
	 */
	@Override
	public int add(ReFinanceExamine reFinanceExamine) {
		reFinanceExamine.setStatus(1);
		int result = reFinanceExamineMapper.insert(reFinanceExamine);
		return result;
	}

	/**
	 * 修改财务核账表
	 */
	@Override
	public int update(ReFinanceExamine reFinanceExamine) {
		reFinanceExamine.setStatus(1);
		int result = reFinanceExamineMapper.update(reFinanceExamine);
		return result;
	}

	/**
	 * 统计财务核账表
	 * countDate：统计的日期，一般是每天
	 * setTime：设置的时间，一般是下午23:59:59
	 */
	@Override
	public void countReFinanceExamine(String countDate,String setTime)throws Exception{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat sdfEithTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//获取当前时间日期
		Calendar calendar = Calendar.getInstance();
		Date oldDate = sdf.parse(countDate);
		calendar.setTime(oldDate);
		calendar.add(Calendar.DAY_OF_MONTH, -1);//传入的日期的前一天
		String countDateYesterday = sdf.format(calendar.getTime());
		Date countDateTime = sdfEithTime.parse(countDate+" "+setTime);//传入的日期时间date

		//查询统计信息
		//根据公司编码统计公司实时资金
		List<Map<String, Object>> accountCountNoCommonUser = reFinanceExamineDiyMapper.countAccountCountForCompany();

		//********历史资金********
		String startTime = countDateYesterday + " 00:00:00";
		String endTime = countDateYesterday + " 23:59:59";
		List<ReFinanceExamine> reFinanceExamineOldList = new ReFinanceExamine()
				.where("A.ExamineTime BETWEEN '"+ startTime +"' AND '" + endTime +"'")
				.queryList();

		//********账户流水********
		String todayStartTime = countDate + " 00:00:00";
		String todayEndTime = countDate + " 23:59:59";
		//根据公司编码统计公司账户流水
		List<Map<String, Object>> countAccountCountForCompanyByFundTurnover = reFinanceExamineDiyMapper.countAccountCountForCompanyByFundTurnover(todayStartTime,todayEndTime);

		logger.info("***********统计财务核账表查询完成，开始更新***********");

		Predicate<List> listNotNull = list-> list!=null && list.size()>0;


		List<ReFinanceExamine> addList = new ArrayList<>();

		//排除普通运营账户的数据
		if(listNotNull.test(accountCountNoCommonUser)){
			for (Map<String, Object> item:accountCountNoCommonUser){
				ReFinanceExamine reFinanceExamine = new ReFinanceExamine();
				//核账实时资金
				BigDecimal realTimeFund = (BigDecimal)item.get("realTimeFund");
				String accountTypeName = item.get("accountTypeName")!=null?item.get("accountTypeName").toString():"";
				//运营公司编码
				String accountCode = item.get("accountCode")!=null?item.get("accountCode").toString():"";
				//运营公司简称
				String accountName = item.get("accountName")!=null?item.get("accountName").toString():"";

				//昨日实时资金
				BigDecimal yesterdayFund = BigDecimal.ZERO;
				if(listNotNull.test(reFinanceExamineOldList)){
					List<ReFinanceExamine> oldListByCode = reFinanceExamineOldList.stream()
							.filter(oldItem->oldItem.getAccountCode().equals(accountCode))
							.collect(Collectors.toList());
					if(oldListByCode.size()>0){
						yesterdayFund = oldListByCode.get(0).getRealTimeFund();
					}
				}
				//今日资金变化 = 核账实时资金 - 昨日实时资金
				BigDecimal fundChange = realTimeFund.subtract(yesterdayFund);

				//今日流水变化
				BigDecimal fundTurnoverChange = BigDecimal.ZERO;
				if(listNotNull.test(countAccountCountForCompanyByFundTurnover)){
					List<Map<String, Object>> listByCode = countAccountCountForCompanyByFundTurnover.stream()
							.filter(theItem->theItem.get("accountCode").equals(accountCode))
							.collect(Collectors.toList());
					if(listByCode.size()>0){
						fundTurnoverChange = (BigDecimal)listByCode.get(0).get("fundTurnover");
					}
				}

				//审核情况（0无误、1有误）
				//有误：今日资金变化!=今日流水变化
				int examineStatus = 0;
				if(fundChange.compareTo(fundTurnoverChange)!=0){
					examineStatus = 1;
				}

				//填入参数
				reFinanceExamine.setAccountCode(accountCode);//账户编码
				reFinanceExamine.setAccountName(accountName);//账户简称
				reFinanceExamine.setExamineTime(countDateTime);//核账时间
				reFinanceExamine.setRealTimeFund(realTimeFund);//核账实时资金
				reFinanceExamine.setYesterdayFund(yesterdayFund);//昨日历史资金
				reFinanceExamine.setFundChange(fundChange);//今日资金变化
				reFinanceExamine.setFundTurnoverChange(fundTurnoverChange);//今日流水变化
				reFinanceExamine.setExamineStatus(examineStatus);//审核情况（0无误、1有误）
				reFinanceExamine.setAccountTypeName(accountTypeName);//账户类型名称
				reFinanceExamine.setStatus(1);
				addList.add(reFinanceExamine);
			}
		}

		//先删除
		reFinanceExamineDiyMapper.deleteFinanceExamineByTime(countDate+" 00:00:00",countDate+" 23:59:59");
		//再新增
		if(addList!=null && addList.size()>0){
			int count = 50;
			for(int i=0;i<addList.size()+count;i=i+count){
				List<ReFinanceExamine> newlist = addList.stream().skip(i).limit(count).collect(Collectors.toList());
				reFinanceExamineDiyMapper.insertReFinanceExamineByList(newlist);//批量新增
			}
		}

	}




	/**
	 * 统计财务核账表----刷数据
	 * countDate：统计的日期，一般是每天
	 * setTime：设置的时间，一般是下午23:59:59
	 */
	@Override
	public void countReFinanceExamineByHistory(String countDate,String setTime)throws Exception{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat sdfEithTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//获取当前时间日期
		Calendar calendar = Calendar.getInstance();
		Date oldDate = sdf.parse(countDate);
		calendar.setTime(oldDate);
		calendar.add(Calendar.DAY_OF_MONTH, -1);//传入的日期的前一天
		String countDateYesterday = sdf.format(calendar.getTime());
		Date countDateTime = sdfEithTime.parse(countDate+" "+setTime);//传入的日期时间date

		//查询统计信息
		//根据公司编码统计公司实时资金
		List<Map<String, Object>> accountCountNoCommonUser = reFinanceExamineDiyMapper.countAccountCountForCompanyByHistory(countDate+ " 00:00:00",countDate+ " 23:59:59");

		//********历史资金********
		String startTime = countDateYesterday + " 00:00:00";
		String endTime = countDateYesterday + " 23:59:59";
		List<ReFinanceExamine> reFinanceExamineOldList = new ReFinanceExamine()
				.where("A.ExamineTime BETWEEN '"+ startTime +"' AND '" + endTime +"'")
				.queryList();

		//********账户流水********
		String todayStartTime = countDate + " 00:00:00";
		String todayEndTime = countDate + " 23:59:59";
		//根据公司编码统计公司账户流水
		List<Map<String, Object>> countAccountCountForCompanyByFundTurnover = reFinanceExamineDiyMapper.countAccountCountForCompanyByFundTurnover(todayStartTime,todayEndTime);

		logger.info("***********统计财务核账表查询完成，开始更新***********");

		Predicate<List> listNotNull = list-> list!=null && list.size()>0;


		List<ReFinanceExamine> addList = new ArrayList<>();

		//排除普通运营账户的数据
		if(listNotNull.test(accountCountNoCommonUser)){
			for (Map<String, Object> item:accountCountNoCommonUser){
				ReFinanceExamine reFinanceExamine = new ReFinanceExamine();
				//核账实时资金
				BigDecimal realTimeFund = (BigDecimal)item.get("realTimeFund");
				String accountTypeName = item.get("accountTypeName")!=null?item.get("accountTypeName").toString():"";
				//运营公司编码
				String accountCode = item.get("accountCode")!=null?item.get("accountCode").toString():"";
				//运营公司简称
				String accountName = item.get("accountName")!=null?item.get("accountName").toString():"";

				//昨日实时资金
				BigDecimal yesterdayFund = BigDecimal.ZERO;
				if(listNotNull.test(reFinanceExamineOldList)){
					List<ReFinanceExamine> oldListByCode = reFinanceExamineOldList.stream()
							.filter(oldItem->oldItem.getAccountCode().equals(accountCode))
							.collect(Collectors.toList());
					if(oldListByCode.size()>0){
						yesterdayFund = oldListByCode.get(0).getRealTimeFund();
					}
				}
				//今日资金变化 = 核账实时资金 - 昨日实时资金
				BigDecimal fundChange = realTimeFund.subtract(yesterdayFund);

				//今日流水变化
				BigDecimal fundTurnoverChange = BigDecimal.ZERO;
				if(listNotNull.test(countAccountCountForCompanyByFundTurnover)){
					List<Map<String, Object>> listByCode = countAccountCountForCompanyByFundTurnover.stream()
							.filter(theItem->theItem.get("accountCode").equals(accountCode))
							.collect(Collectors.toList());
					if(listByCode.size()>0){
						fundTurnoverChange = (BigDecimal)listByCode.get(0).get("fundTurnover");
					}
				}

				//审核情况（0无误、1有误）
				//有误：今日资金变化!=今日流水变化
				int examineStatus = 0;
				if(fundChange.compareTo(fundTurnoverChange)!=0){
					examineStatus = 1;
				}

				//填入参数
				reFinanceExamine.setAccountCode(accountCode);//账户编码
				reFinanceExamine.setAccountName(accountName);//账户简称
				reFinanceExamine.setExamineTime(countDateTime);//核账时间
				reFinanceExamine.setRealTimeFund(realTimeFund);//核账实时资金
				reFinanceExamine.setYesterdayFund(yesterdayFund);//昨日历史资金
				reFinanceExamine.setFundChange(fundChange);//今日资金变化
				reFinanceExamine.setFundTurnoverChange(fundTurnoverChange);//今日流水变化
				reFinanceExamine.setExamineStatus(examineStatus);//审核情况（0无误、1有误）
				reFinanceExamine.setAccountTypeName(accountTypeName);//账户类型名称
				reFinanceExamine.setStatus(1);
				addList.add(reFinanceExamine);
			}
		}

		//先删除
		reFinanceExamineDiyMapper.deleteFinanceExamineByTime(countDate+" 00:00:00",countDate+" 23:59:59");
		//再新增
		if(addList!=null && addList.size()>0){
			int count = 50;
			for(int i=0;i<addList.size()+count;i=i+count){
				List<ReFinanceExamine> newlist = addList.stream().skip(i).limit(count).collect(Collectors.toList());
				reFinanceExamineDiyMapper.insertReFinanceExamineByList(newlist);//批量新增
			}
		}

	}

	/**
	 * 根据时间删除财务核账表
	 */
	@Override
	public int del(String startTime,String endTime) {
		return reFinanceExamineDiyMapper.deleteFinanceExamineByTime(startTime,endTime);
	}


}
